<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <img src="@/assets/logo/logo1.png" alt="" class="logo" />
      <!-- <h3 class="title">数智科研管理服务平台</h3> -->
      <div class="login-type">
        <span
          v-for="item in loginTypes"
          :key="item.value"
          :class="{ active: loginType == item.value }"
          @click="loginType = item.value"
          >{{ item.label }}</span
        >
      </div>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
        >
          <template #prefix>
            <img src="@/assets/images/login-user.png" alt="" class="inline-block" />
            <div class="mx-[10px] h-[24px] w-[1px]" style="background: #e5e5e5"></div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <img src="@/assets/images/login-password.png" alt="" class="inline-block" />
            <div class="ml-[11px] mr-[10px] h-[24px] w-[1px]" style="background: #e5e5e5"></div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 258px"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon
              icon-class="validCode"
              color="#54A8FF"
              style="width: 28px; height: 100%"
              class="el-input__icon"
            />
            <div class="ml-[4px] mr-[10px] h-[24px] w-[1px]" style="background: #e5e5e5"></div>
          </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" class="mb-[20px]">记住密码</el-checkbox>
      <el-form-item>
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          class="w-full h-[50px]"
          style="font-size: 16px"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
//登录类型
const loginTypes = [
  {
    label: "科研人员",
    value: 1,
  },
  {
    label: "评审专家",
    value: 2,
  },
];
const loginType = ref(1);
// 验证码开关
const captchaEnabled = ref(false);

const redirect = ref(undefined);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore
        .login({ ...loginForm.value, type: loginType.value })
        .then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({ path: redirect.value || "/", query: otherQueryParams });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

getCode();
getCookie();
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: cover;
}
.logo {
  display: block;
  margin: 0 auto 40px;
}
.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #fff;
  font-size: 32px;
  letter-spacing: 6px;
}
.login-type {
  display: flex;
  justify-content: center;
  color: #fff;
  font-size: 22px;
  margin-bottom: 20px;
  letter-spacing: 5px;
  span {
    cursor: pointer;
    margin-right: 20px;
    position: relative;
    padding-bottom: 10px;
    &.active {
      font-weight: bold;
      &::after {
        position: absolute;
        bottom: 0;
        display: block;
        content: "";
        width: 101px;
        height: 2px;
        background: #fff;
      }
      // border-bottom: 2px solid #fff;
    }
  }
}
.login-form {
  margin-left: 18%;
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.2);
  width: 460px;
  padding: 35px 35px 15px 35px;
  .el-input {
    font-size: 15px;
    height: 50px;
    input {
      height: 50px;
    }
  }
}
.login-code {
  height: 50px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  width: 120px;
  height: 50px;
  margin-left: 12px;
  border-radius: 4px;
}
:deep(.el-checkbox__label) {
  color: #fff;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #fff;
  border-color: #fff;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner:after) {
  border-width: 2px;
  border-color: var(--el-checkbox-checked-bg-color);
}
:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #fff;
}
</style>
